﻿using HardcoreGame.Common.Entities;
using HardcoreGame.Common.Systems;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;

namespace HardcoreGame.Common.GlobalTiles
{
    public class BookcaseGlobalTile : GlobalTile
    {
        public override void RightClick(int i, int j, int type)
        {
            if (type == 101)
            {
                BookcaseEntity entity = EnsureEntity(i, j);
                if (Main.netMode != NetmodeID.Server)
                {
                    BookcaseUISystem.BookcaseUI.SetCurrentEntity(entity);
                    BookcaseUISystem.BookcaseInterface.SetState(BookcaseUISystem.BookcaseUI);
                    Main.playerInventory = true;
                }
            }
        }
        public override void MouseOver(int i, int j, int type)
        {
            if (type == 101)
            {
                Player localPlayer = Main.LocalPlayer;
                localPlayer.cursorItemIconEnabled = true;
                localPlayer.cursorItemIconID = 149;
            }
        }
        private static BookcaseEntity EnsureEntity(int i, int j)
        {
            Tile tile = Main.tile[i, j];
            int left = i - tile.TileFrameX / 18 % 3;
            int top = j - tile.TileFrameY / 18 % 4;
            Point16 pos;
            pos = new(left, top);
            BookcaseEntity be;
            if (TileEntity.ByPosition.TryGetValue(pos, out TileEntity te))
            {
                be = te as BookcaseEntity;
                if (be != null)
                {
                    return be;
                }
            }
            TileEntity.PlaceEntityNet(left, top, ModContent.TileEntityType<BookcaseEntity>());
            be = (BookcaseEntity)TileEntity.ByPosition[pos];
            return be;
        }
    }
}